<template>
    <div class="position-admin">
        <a-button type="primary" class="btn-add" @click="onAdd">新增</a-button>
        <a-table :columns="columns" :data-source="list" rowKey="id"
            bordered
            class="table"
            :loading="loading"
            :pagination="pagination"
            @change="onPageChange"
        >
            <span slot="action" slot-scope="text, record">
                <span class="action-btn" @click="onEdit(record)">修改</span>
                <span class="action-btn" @click="onDelete(record.id, record.name)">删除</span>
            </span>
        </a-table>
        <a-modal :title="type==='add'?'新增职务':'修改职务'"
            :visible="visible"
            @cancel="onCancel"
            :footer="null"
        >
            <a-form :form="form" @submit="onSubmit"> 
                <a-form-item label="职务名称"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                >
                    <a-input placeholder="请输入职务名称" 
                         v-decorator="['name',
                            { rules: [
                                { required: true, message: '请输入职务名称' },
                            ] }
                        ]"
                    />
                </a-form-item>
                <a-form-item label="职务描述"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                >
                    <a-textarea placeholder="请输入职务描述" :rows="3"
                        v-decorator="['description',
                            { rules: [
                                { required: true, message: '请输入职务描述' },
                            ] }
                        ]"
                    />
                </a-form-item>
                <a-form-item :wrapper-col="{offset: 6}">
                    <a-button type="primary" html-type="submit" :loading="addLoading">提交</a-button>
                </a-form-item>
            </a-form>

        </a-modal>
    </div>
</template>

<script>
import { getRoles, addRole, updateRole, deleteRole } from '@/services';

const columns = [
    { title: '职务名称', dataIndex: 'name' },
    { title: '职务描述', dataIndex: 'description' },
    { title: '操作', key: 'action', align: 'center', scopedSlots: { customRender: 'action' } },
]

export default {
    name: 'PositionAdmin',
    data(){
        return {
            visible: false,
            addLoading: false,
            formItemLayout: {
                labelCol: { span: 6 },
                wrapperCol: { span: 16 },
            },
            type: '',
            columns,
            loading: false,
            list: [],
            pagination: {},
            form: this.$form.createForm(this),
            editId: ''
        }
    },
    mounted(){
        this.getRolesList();
    },
    methods: {
        // 新增按钮
        onAdd(){
            this.visible = true;
            this.type = "add"
        },
        // 删除按钮
        onDelete(id, text){
            const _that = this;
            this.$confirm({
                title: `确认删除 ${text} 吗? `,
                okText: "删除",
                okType: 'danger',
                cancelText: "取消",
                onOk(){
                    _that.onDeleteRole(id)
                }
            })
        },
        // 关闭modal
        onCancel(){
            this.visible = false;
            this.form.resetFields();
        },
        // 获取职务列表
        async getRolesList(page = 1){
            this.loading = true;
            let res = await getRoles({ page });
            this.loading = false;
            if(res.responseObject){
                let pagination = { ...this.pagination };
                let { Count, Result } = res.responseObject;
                this.list = Result;
                pagination.total = Count;
                pagination.current = page;
                pagination.pageSize = 10;
                pagination.showTotal = (total, range) => `共找到 ${total} 条数据`
                this.pagination = pagination;
            }
        },
        // 点击提交按钮
        onSubmit(e){
            e.preventDefault();
            const _that = this;
            const { type, editId } = this;
            this.form.validateFields((err, values) => {
                if (!err) {
                    if(type === 'add') _that.onAddRole(values);
                    else if(type === 'edit') {
                        _that.onUpdateRole(Object.assign(values, { id: editId }))
                    }
                }
            })
        },
        // 新增职务
        async onAddRole (params) {
            this.addLoading = true;
            let res = await addRole(params);
            this.addLoading = false;
            const _that = this;
            if(res.success) {
                this.$message.success('新增职务成功', 1, ()=>{
                    _that.onCancel();
                    _that.getRolesList(_that.pagination.current);
                })
            }else if(!res.success && res.errorMessage){
                this.$message.error(res.errorMessage, 1)
            }
        },
        // 切换分页
        onPageChange(pagination, filters, sorter){
            let { current, pageSize } = pagination;
            this.getRolesList(current);
        },
        // 修改按钮
        onEdit(params){
            this.form.getFieldDecorator('name');
            this.form.getFieldDecorator('description');
            this.type = 'edit';
            this.visible = true;
            this.editId = params.id;
            this.form.setFieldsValue({
                name: params.name,
                description: params.description,
            })
        },
        // 修改职务
        async onUpdateRole(params){
            this.addLoading = true;
            let res = await updateRole(params);
            this.addLoading = false;
            const _that = this;
            if(res.success) {
                this.$message.success('修改职务成功', 1, ()=>{
                    _that.onCancel();
                    _that.getRolesList(_that.pagination.current);
                })
            }else if(!res.success && res.errorMessage){
                this.$message.error(res.errorMessage, 1)
            }
        },
        // 删除职务
        async onDeleteRole(id){
            this.loading = true;
            let res = await deleteRole(id);
            const _that = this;
            if(res.success){
                this.$message.success('删除部门成功', 1, ()=>{
                    _that.getRolesList(_that.pagination.count > 11 ? _that.pagination.current : 1);
                })
            }else if(res.errorMessage){
                this.loading = false;
                this.$message.error(res.errorMessage, 1)
            }
        }
    }
}
</script>
<style lang="less" scoped>
@import '../global.less';
    .position-admin{
        padding: 20px 30px;
        // margin: 0 auto;
        // width: 600px;
        .btn-add{
            margin-bottom: 20px;
        }
        .table{
            width: 800px;
            .action-btn{
                color: @primary;
                margin: 0 10px;
                cursor: pointer;
            }
        }
    }
</style>